<script setup lang="ts">
import type { Action } from 'element-plus'
import type {
  ApplicationModelIndicator,
} from '@/types/modules/application-models'
import IndicatorsBox from '@/views/ApplicationModelConfigs/components/IndicatorsBox/IndicatorsBox.vue'
import { useTableList } from './tableList'
import { useIndicators } from './indicator'
import EnergyUnitCascader from '@/components/EnergyUnitCascader/EnergyUnitCascader.vue'

const includeSub = ref(false)
const pointId = ref<number>()
const queryText = ref('')
const {
  columns,
  loading,
  tableData,
  pagination,
  queryList,
} = useTableList()

const {
  indicatorLoading,
  indicators,
  getIndicatorsOfPoint,
  modelIndicators,
  setModelIndicators,
  modelIndicatorLoading,
  getIndicatorsOfModel,
  confirmDel,
  bindIndicator,
  unbindIndicator,
} = useIndicators()

const [modelPoint, setModelPoint] = useState<any>(
  null,
)

const selectedIndicatorsKeyword = ref('')
const unselectedIndicatorsKeyword = ref('')
const selectedIndicators = computed(() => {
  return unref(modelIndicators)
})
const selectedIndicatorsFiltered = computed(() => {
  const keyword = unref(selectedIndicatorsKeyword)
  return unref(selectedIndicators).filter(v =>
    v.indicatorName.includes(keyword),
  )
})
const unselectedIndicators = computed(() => {
  const modelId = unref(modelPoint)?.id
  const d = unref(includeSub)
    ? unref(selectedIndicators).filter(
      v => v.applicationModelId === modelId,
    )
    : unref(selectedIndicators)
  return unref(indicators).filter(
    v => !d.some(vv => vv.indicatorId === v.indicatorId),
  )
})
const unselectedIndicatorsFiltered = computed(() => {
  const keyword = unref(unselectedIndicatorsKeyword)
  return unref(unselectedIndicators).filter(v =>
    v.indicatorName.includes(keyword),
  )
})
const selectedIndicatorsChecked = ref<
  ApplicationModelIndicator[]
>([])
const unselectedIndicatorsChecked = ref<
  ApplicationModelIndicator[]
>([])

async function toLeft() {
  const d = unref(selectedIndicatorsChecked)
  if (d.length > 0) {
    const action: Action = await confirmDel().catch(e => e)
    if (action !== 'confirm')
      return
    const modelId = unref(modelPoint)?.id
    if (!modelId) {
      ElMessage.warning('请先选择设备')
      return
    }
    // 删除选中的指标（更新模型配置）
    try {
      await unbindIndicator(
        modelId,
        d.map(o => o.indicatorId),
      )
      await nextTick()
      setModelIndicators(
        unref(modelIndicators).filter(
          i => !d.some(v => v.id === i.id),
        ),
      )
      // 刷新模型指标
      const old = { ...unref(modelPoint) }
      setModelPoint(null)
      setTimeout(() => {
        setModelPoint(old)
      }, 20)
    }
    catch (e) {}
  }
}
async function toRight() {
  const d = unref(unselectedIndicatorsChecked)
  if (d.length > 0) {
    // 添加选中的指标（更新模型配置）
    try {
      const modelId = unref(modelPoint)?.id
      if (!modelId) {
        ElMessage.warning('请先选择设备')
        return
      }
      await bindIndicator(
        modelId,
        d.map(o => o.indicatorId),
      )
      await nextTick()
      setModelIndicators(unref(modelIndicators).concat(d))
      // 刷新模型指标
      const old = { ...unref(modelPoint) }
      setModelPoint(null)
      setTimeout(() => {
        setModelPoint(old)
      }, 20)
    }
    catch (e) {}
  }
}

async function getTableData() {
  queryList({
    pointId: pointId.value,
    queryText: queryText.value,
  })
}

async function clickSearch() {
  pagination.pageNumber = 1
  await nextTick()
  await getTableData()
}

// async function whenPointLoaded(id: number) {
//   if (id) {
//     pointId.value = id
//     await nextTick()
//     clickSearch()
//   }
// }

async function whenRowClick(row: any) {
  const mp = unref(modelPoint)
  if (mp && mp.id && row.id === mp.id) {
    getIndicatorsOfModel(mp.id)
    if (mp?.pointId) {
      getIndicatorsOfPoint(mp.pointId)
    }
  }

  setModelPoint(row)
}

watchEffect(() => {
  const mp = unref(modelPoint)
  if (mp?.id) {
    getIndicatorsOfModel(mp.id)
  }
})
watchEffect(() => {
  const mp = unref(modelPoint)
  if (mp?.pointId) {
    getIndicatorsOfPoint(mp.pointId)
  }
})

onMounted(() => {
  clickSearch()
})
</script>

<template>
  <div class="box-border h-full w-full flex p-4">
    <div class="h-full w-[700px] flex flex-col">
      <div class="mb-4 flex flex-nowrap items-center gap-4">
        <span>用能单元</span>
        <EnergyUnitCascader v-model="pointId" class="!w-50" />
        <span>关键字</span>
        <ElInput v-model="queryText" clearable placeholder="编号或名称" class="w-40" />
        <SearchButton @click="clickSearch" />
      </div>
      <TableLists
        :lists="tableData" :loading="loading"
        :columns="columns" :show-toolbox="false"
        highlight-current-row
        @row-click="whenRowClick"
      />
      <ListsPagination
        v-model:page-num="pagination.pageNumber"
        v-model:page-size="pagination.pageSize"
        :total="pagination.total"
        @change="getTableData"
      />
    </div>
    <div class="ml-4 w-1/2 flex-auto">
      <div class="h-full flex flex-col">
        <div class="configs-box max-h-1/2 flex flex-col">
          <div class="width-fill relative flex items-center">
            <h3 class="flex-shrink-0 !m-0">
              可配置的指标
            </h3>
          </div>
          <div
            class="mt-4 flex flex-auto flex-col overflow-auto border rounded-sm"
          >
            <div class="indicator-filter mb-4 flex-shrink-0">
              <ElInput
                v-model="unselectedIndicatorsKeyword"
                placeholder="关键字"
                class="free"
                clearable
              />
            </div>
            <div
              class="indicator-wrapper flex-auto overflow-auto"
            >
              <IndicatorsBox
                v-model="unselectedIndicatorsChecked"
                :loading="indicatorLoading"
                :data="unselectedIndicatorsFiltered"
              />
            </div>
          </div>
        </div>
        <div
          class="my-4 flex flex-shrink-0 items-center justify-center"
        >
          <ElTooltip content="添加配置" placement="top">
            <ElButton type="primary" @click="toRight">
              添加
            </ElButton>
          </ElTooltip>
          <ElTooltip content="移除配置" placement="top">
            <ElButton type="danger" @click="toLeft">
              删除
            </ElButton>
          </ElTooltip>
        </div>
        <div class="configs-box max-h-[400px] flex flex-auto flex-col">
          <div class="relative w-full flex items-center">
            <h3 class="!margin-0 flex-shrink-0">
              已配置的指标
            </h3>
          </div>
          <div
            class="mt-4 flex flex-auto flex-col overflow-auto border rounded-sm"
          >
            <div class="indicator-filter mb-4 flex-shrink-0">
              <ElInput
                v-model="selectedIndicatorsKeyword"
                placeholder="关键字"
                class="free"
                clearable
              />
            </div>
            <div
              class="indicator-wrapper flex-auto overflow-auto"
            >
              <IndicatorsBox
                v-model="selectedIndicatorsChecked"
                :loading="modelIndicatorLoading"
                :data="selectedIndicatorsFiltered"
              />
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
